from app import db
from datetime import datetime
import json

class QuestionCategory(db.Model):
    """题目分类模型"""
    __tablename__ = 'question_categories'
    
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False, comment='分类名称')
    description = db.Column(db.Text, comment='分类描述')
    sort_order = db.Column(db.Integer, default=0, comment='排序')
    is_active = db.Column(db.Boolean, default=True, comment='是否激活')
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    # 关联关系
    questions = db.relationship('Question', backref='category', lazy='dynamic')
    
    def __repr__(self):
        return f'<QuestionCategory {self.name}>'
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'name': self.name,
            'description': self.description,
            'sort_order': self.sort_order,
            'is_active': self.is_active,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }

class Question(db.Model):
    """题目模型"""
    __tablename__ = 'questions'
    
    id = db.Column(db.Integer, primary_key=True)
    category_id = db.Column(db.Integer, db.ForeignKey('question_categories.id'), nullable=False, comment='分类ID')
    type = db.Column(db.Enum('single_choice', 'multiple_choice', 'true_false', 'fill_blank'), nullable=False, comment='题目类型')
    difficulty = db.Column(db.Enum('easy', 'medium', 'hard'), default='medium', comment='难度等级')
    title = db.Column(db.Text, nullable=False, comment='题目标题')
    content = db.Column(db.Text, comment='题目内容')
    options = db.Column(db.JSON, comment='选项（JSON格式）')
    correct_answer = db.Column(db.Text, nullable=False, comment='正确答案')
    explanation = db.Column(db.Text, comment='答案解析')
    score = db.Column(db.Integer, default=10, comment='分值')
    is_active = db.Column(db.Boolean, default=True, comment='是否激活')
    created_by = db.Column(db.Integer, db.ForeignKey('admins.id'), nullable=False, comment='创建者ID')
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    # 关联关系
    exam_questions = db.relationship('ExamQuestion', backref='question', lazy='dynamic')
    
    def __repr__(self):
        return f'<Question {self.title[:50]}...>'
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'category_id': self.category_id,
            'category': self.category.to_dict() if self.category else None,
            'type': self.type,
            'difficulty': self.difficulty,
            'title': self.title,
            'content': self.content,
            'options': self.options,
            'correct_answer': self.correct_answer,
            'explanation': self.explanation,
            'score': self.score,
            'is_active': self.is_active,
            'created_by': self.created_by,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }
    
    def to_dict_for_exam(self):
        """转换为考试用的字典（不包含正确答案）"""
        return {
            'id': self.id,
            'type': self.type,
            'title': self.title,
            'content': self.content,
            'options': self.options,
            'score': self.score
        }
    
    def check_answer(self, user_answer):
        """检查答案是否正确"""
        if self.type == 'single_choice':
            return user_answer == self.correct_answer
        elif self.type == 'multiple_choice':
            # 多选题答案可能是逗号分隔的字符串
            if isinstance(self.correct_answer, str):
                correct_answers = set(self.correct_answer.split(','))
            else:
                correct_answers = set(self.correct_answer)
            
            if isinstance(user_answer, str):
                user_answers = set(user_answer.split(','))
            else:
                user_answers = set(user_answer)
            
            return user_answers == correct_answers
        elif self.type == 'true_false':
            return user_answer == self.correct_answer
        elif self.type == 'fill_blank':
            # 填空题答案可能是多个，用逗号分隔
            if isinstance(self.correct_answer, str):
                correct_answers = [ans.strip() for ans in self.correct_answer.split(',')]
            else:
                correct_answers = self.correct_answer
            
            if isinstance(user_answer, str):
                user_answers = [ans.strip() for ans in user_answer.split(',')]
            else:
                user_answers = user_answer
            
            return user_answers == correct_answers
        
        return False 